import { getPolygon, type Paint } from '../utils';
import Shape from './base';

class Rectangle extends Shape {
  DrawingStart(e: mapboxgl.MapMouseEvent): Paint | undefined {
    this.enter();
    this.paint = {
      type: 'rectangle',
      coordinates: [],
    };
    this.paint.coordinates.push([e.lngLat.lng, e.lngLat.lat]);
    this.paint.coordinates.push([e.lngLat.lng, e.lngLat.lat]);
    return this.retPaint();
  }
  Drawing(e: mapboxgl.MapMouseEvent): Paint | undefined {
    if (this.paint) {
      this.paint.coordinates[1] = [e.lngLat.lng, e.lngLat.lat];
      const poly = getPolygon(this.paint);
      poly && this.draw2Map(poly.geometry.coordinates as GeoJSON.Position[][]);
    }
    return this.retPaint();
  }
  DrawingEnd(_e: mapboxgl.MapMouseEvent): Paint | undefined {
    this.exit();
    return this.retPaint();
  }

  draw2Map(positions: GeoJSON.Position[][]) {
    // 绘制到地图
    const source = this.map?.getSource(this.sourceId) as mapboxgl.GeoJSONSource;
    source?.setData?.({
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: positions[0],
      },
      properties: {},
    });
  }
}

export default Rectangle;
